import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface AppConfig {
  title: string
  theme: 'light' | 'dark'
  language: 'zh-CN' | 'en-US'
  sidebarCollapsed: boolean
}

export const useAppStore = defineStore('app', () => {
  const config = ref<AppConfig>({
    title: 'RegoTop Admin',
    theme: 'light',
    language: 'zh-CN',
    sidebarCollapsed: false
  })

  const loading = ref(false)
  const notifications = ref<Array<{
    id: string
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message: string
    duration?: number
    timestamp: number
  }>>([])

  // 设置加载状态
  const setLoading = (state: boolean) => {
    loading.value = state
  }

  // 切换侧边栏
  const toggleSidebar = () => {
    config.value.sidebarCollapsed = !config.value.sidebarCollapsed
    localStorage.setItem('sidebarCollapsed', String(config.value.sidebarCollapsed))
  }

  // 设置主题
  const setTheme = (theme: 'light' | 'dark') => {
    config.value.theme = theme
    localStorage.setItem('theme', theme)
    
    // 更新HTML类名
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 设置语言
  const setLanguage = (language: 'zh-CN' | 'en-US') => {
    config.value.language = language
    localStorage.setItem('language', language)
  }

  // 添加通知
  const addNotification = (notification: Omit<typeof notifications.value[0], 'id' | 'timestamp'>) => {
    const id = Date.now().toString()
    const newNotification = {
      ...notification,
      id,
      timestamp: Date.now(),
      duration: notification.duration || 4000
    }
    
    notifications.value.push(newNotification)
    
    // 自动移除通知
    if (newNotification.duration > 0) {
      setTimeout(() => {
        removeNotification(id)
      }, newNotification.duration)
    }
    
    return id
  }

  // 移除通知
  const removeNotification = (id: string) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
    }
  }

  // 清空所有通知
  const clearNotifications = () => {
    notifications.value = []
  }

  // 初始化应用配置
  const initConfig = () => {
    // 从localStorage恢复配置
    const savedSidebarCollapsed = localStorage.getItem('sidebarCollapsed')
    if (savedSidebarCollapsed !== null) {
      config.value.sidebarCollapsed = savedSidebarCollapsed === 'true'
    }

    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'
    if (savedTheme) {
      setTheme(savedTheme)
    }

    const savedLanguage = localStorage.getItem('language') as 'zh-CN' | 'en-US'
    if (savedLanguage) {
      config.value.language = savedLanguage
    }
  }

  return {
    config,
    loading,
    notifications,
    setLoading,
    toggleSidebar,
    setTheme,
    setLanguage,
    addNotification,
    removeNotification,
    clearNotifications,
    initConfig
  }
})